package com.sunmouse.thread.download;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.URL;

import com.sunmouse.util.PrintUtil;

public class DownloadThread extends Thread {
	public static final int READ_SIZE = 256 * 1024;// 256k
	private long start;
	private long readSize;
	private String remoteUrl;
	private URL url;
	private File output;

	@Override
	public void run() {
		super.run();
		PrintUtil.pln("-----here");
		try {
			//long cp = 0;
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			conn.setAllowUserInteraction(true);
			conn.setRequestProperty("Range", "bytes=" + start + "-" + (start
					+ readSize));
			int status=conn.getResponseCode();
			PrintUtil.pln("status="+status);
			if (conn.getResponseCode() == 206) {
				BufferedInputStream bis = new BufferedInputStream(
						conn.getInputStream());
				RandomAccessFile rafOut = new RandomAccessFile(output, "rw");
				// bis.mark((int) start);
				// bis.skip(start);
				rafOut.seek(start);
				int len = 0;
				byte[] b = new byte[READ_SIZE];
				while ((len = bis.read(b)) != -1) {
					rafOut.write(b, 0, len);
//					cp += len;
//					if (cp == readSize)
//						return;
					PrintUtil.pln("loading...");
				}
				rafOut.close();
				bis.close();
				conn.disconnect();
				PrintUtil.pln("-----start=" + start + "----finish");
			}
		} catch (IOException e) {
			e.printStackTrace();
		}

	}

	public DownloadThread(long start, long end, URL url,
			File output) {
		super();
		this.start = start;
		this.readSize = end;
		this.url = url;
		this.output = output;
	}
}
